<template>
  <div class="tabs-demo-container">
    <el-card class="demo-card">
      <div slot="header" class="card-header">
        <i class="el-icon-cloud"></i>
        <span class="header-text">对象存储配置 (Object Storage Configuration)</span>

        <!-- 新增：默认存储服务器选择区 -->
        <!-- 默认存储服务器选择区 -->
        <div class="default-storage-selector">
          <span class="default-storage-text">默认存储服务器：</span>
          <el-select v-model="defaultStorageType" placeholder="选择默认存储服务器（默认：本地存储）" 
            @change="handleDefaultStorageChange"
            size="small"
            >
            <el-option label="本地存储" value="local"></el-option> <!-- 新增本地存储选项 -->
            <el-option label="阿里云OSS" value="aliyun"></el-option>
            <el-option label="七牛云" value="qiniu"></el-option>
            <el-option label="腾讯云COS" value="tencent"></el-option>
          </el-select>
          <el-tooltip content="选择后，文件上传将默认使用该存储服务器（未选择时默认本地存储）"> <!-- 调整提示 -->
            <i class="el-icon-question-circle"></i>
          </el-tooltip>
        </div>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="storage-tabs">
        <!-- 阿里云OSS配置 -->
        <el-tab-pane label="阿里云OSS (Aliyun OSS)" name="aliyun">
          <div class="tab-content">
            <el-form ref="aliyunForm" :model="aliyunConfig" :rules="aliyunRules" label-width="180px"
              class="config-form">
              <el-form-item label="Endpoint" prop="endpoint">
                <el-input v-model="aliyunConfig.endpoint" placeholder="例如：oss-cn-beijing.aliyuncs.com"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="AccessKeyId" prop="keyid">
                <el-input v-model="aliyunConfig.keyid" placeholder="例如：LTAI5t7xxxxxxxxxQqfxxxx"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="AccessKeySecret" prop="keysecret">
                <el-input v-model="aliyunConfig.keysecret" placeholder="例如：8txxxxxxxxxxxxxxxxxxxxxxxxxWv"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="Bucket名称" prop="bucketname">
                <el-input v-model="aliyunConfig.bucketname" placeholder="例如：my-bucket-2023"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item class="form-actions">
                <el-button type="primary" @click="handleTest('aliyun')" style="margin-right: 10px;">测试连接</el-button>
                <el-button type="primary" @click="handleConfirm('aliyunForm', 'aliyun')">保存配置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 七牛云配置 -->
        <el-tab-pane label="七牛云 (Qiniu Cloud)" name="qiniu">
          <div class="tab-content">
            <el-form ref="qiniuForm" :model="qiniuConfig" :rules="qiniuRules" label-width="180px" class="config-form">
              <el-form-item label="AccessKey" prop="accessKey">
                <el-input v-model="qiniuConfig.accessKey" placeholder="例如：YPxxxxxxxxxxxxxxxxxxxxxLT"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="SecretKey" prop="secretKey">
                <el-input v-model="qiniuConfig.secretKey" placeholder="例如：Qxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5z"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="存储空间名称" prop="bucket">
                <el-input v-model="qiniuConfig.bucket" placeholder="例如：my-qiniu-bucket" class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="域名" prop="domain">
                <el-input v-model="qiniuConfig.domain" placeholder="例如：img.example.com" class="form-input"></el-input>
              </el-form-item>
              <el-form-item class="form-actions">
                <el-button type="primary" @click="handleTest('qiniu')" style="margin-right: 10px;">测试连接</el-button>
                <el-button type="primary" @click="handleConfirm('qiniuForm', 'qiniu')">保存配置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 腾讯云COS配置 -->
        <el-tab-pane label="腾讯云COS (Tencent Cloud COS)" name="tencent">
          <div class="tab-content">
            <el-form ref="tencentForm" :model="tencentConfig" :rules="tencentRules" label-width="180px"
              class="config-form">
              <el-form-item label="SecretId" prop="secretId">
                <el-input v-model="tencentConfig.secretId" placeholder="例如：AKIDz8xxxxxxxxxxxxxxxxxxxxxxxxxv"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="SecretKey" prop="secretKey">
                <el-input v-model="tencentConfig.secretKey" placeholder="例如：rxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxj"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="Bucket名称" prop="bucket">
                <el-input v-model="tencentConfig.bucket" placeholder="例如：mybucket-1250000000"
                  class="form-input"></el-input>
              </el-form-item>
              <el-form-item label="地域" prop="region">
                <el-input v-model="tencentConfig.region" placeholder="例如：ap-guangzhou" class="form-input"></el-input>
              </el-form-item>
              <el-form-item class="form-actions">
                <el-button type="primary" @click="handleTest('tencent')" style="margin-right: 10px;">测试连接</el-button>
                <el-button type="primary" @click="handleConfirm('tencentForm', 'tencent')">保存配置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import {
  getAliyunConfig,
  saveAliyunConfig,
  getQiniuConfig,
  saveQiniuConfig,
  getTencentConfig,
  saveTencentConfig,
  testStorageConnection,
  getDefaultStorage,
  saveDefaultStorage
} from '@/api/storage';

export default {
  data() {
    // 通用必填验证规则
    const requiredRule = {
      required: true,
      message: '此字段为必填项',
      trigger: 'blur'
    };

    return {
      activeTab: 'aliyun',
      defaultStorageType: '',

      // 阿里云配置
      aliyunConfig: {
        endpoint: '',
        keyid: '',
        keysecret: '',
        bucketname: ''
      },
      aliyunRules: {
        endpoint: [requiredRule],
        keyid: [requiredRule],
        keysecret: [requiredRule],
        bucketname: [requiredRule]
      },

      // 七牛云配置
      qiniuConfig: {
        accessKey: '',
        secretKey: '',
        bucket: '',
        domain: ''
      },
      qiniuRules: {
        accessKey: [requiredRule],
        secretKey: [requiredRule],
        bucket: [requiredRule],
        domain: [requiredRule]
      },

      // 腾讯云配置
      tencentConfig: {
        secretId: '',
        secretKey: '',
        bucket: '',
        region: ''
      },
      tencentRules: {
        secretId: [requiredRule],
        secretKey: [requiredRule],
        bucket: [requiredRule],
        region: [requiredRule]
      }
    };
  },
  created() {
    // 页面加载时获取已保存的配置
    this.loadConfigs();
    this.loadDefaultStorage();
  },
  methods: {
 // 加载默认存储服务器（核心修改）
 async loadDefaultStorage() {
      try {
        const res = await getDefaultStorage();
        // 如果后端返回空（未配置过），则默认使用本地存储
        this.defaultStorageType = res?.data || 'local'; 
      } catch (error) {
        console.error('加载默认存储配置失败:', error);
        // 异常时也默认使用本地存储
        this.defaultStorageType = 'local';
      }
    },
    
    // 处理默认存储服务器变更（兼容本地存储）
    async handleDefaultStorageChange(type) {
      // 本地存储无需校验配置（跳过配置完整性检查）
      if (type === 'local') {
        try {
          await saveDefaultStorage(type);
          this.$message.success('默认存储服务器已切换为本地存储');
        } catch (error) {
          console.error('保存默认存储配置失败:', error);
          this.$message.error('切换默认存储服务器失败，请稍后重试');
        }
        return;
      }
      
      // 其他存储类型仍需校验配置（原有逻辑）
      const config = this.getConfigByType(type);
      const isConfigured = Object.values(config).every(value => value !== '');
      
      if (!isConfigured) {
        this.$message.warning(`请先完成${this.getCloudName(type)}的配置`);
        this.$nextTick(() => {
          this.defaultStorageType = this.defaultStorageType || 'local';  // 恢复为本地
        });
        return;
      }
      
      // 保存其他存储类型（原有逻辑）
      try {
        await saveDefaultStorage(type);
        this.$message.success(`默认存储服务器已切换为${this.getCloudName(type)}`);
      } catch (error) {
        console.error('保存默认存储配置失败:', error);
        this.$message.error('切换默认存储服务器失败，请稍后重试');
      }
    },
    
    // 辅助方法：补充本地存储的名称映射
    getCloudName(type) {
      const names = {
        'local': '本地存储',  // 新增本地存储名称
        'aliyun': '阿里云OSS',
        'qiniu': '七牛云',
        'tencent': '腾讯云COS'
      };
      return names[type] || type;
    },

    // 加载所有配置
    async loadConfigs() {
      try {
        // 加载阿里云配置
        const aliyunData = await getAliyunConfig();
        if (aliyunData) {
          this.aliyunConfig = aliyunData;
        }

        // 加载七牛云配置
        const qiniuData = await getQiniuConfig();
        if (qiniuData) {
          this.qiniuConfig = qiniuData;
        }

        // 加载腾讯云配置
        const tencentData = await getTencentConfig();
        if (tencentData) {
          this.tencentConfig = tencentData;
        }
      } catch (error) {
        console.error('加载配置失败:', error);
        this.$message.error('加载配置失败，请稍后重试');
      }
    },

    // 切换标签页
    handleTabClick(tab) {
      console.log('切换到标签页: ', tab.name);
    },

    // 确认保存配置
    async handleConfirm(formName, type) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let result, cloudName;
            // 根据类型保存不同的配置
            switch (type) {
              case 'aliyun':
                result = await saveAliyunConfig(this.aliyunConfig);
                cloudName = '阿里云OSS';
                break;
              case 'qiniu':
                result = await saveQiniuConfig(this.qiniuConfig);
                cloudName = '七牛云';
                break;
              case 'tencent':
                result = await saveTencentConfig(this.tencentConfig);
                cloudName = '腾讯云COS';
                break;
            }

            if (result) {
              this.$message.success(`${cloudName}配置保存成功`);
            }
          } catch (error) {
            console.error('保存配置失败:', error);
            this.$message.error('保存配置失败，请稍后重试');
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    // 测试连接
    async handleTest(type) {
      let config, cloudName;

      // 获取对应类型的配置
      switch (type) {
        case 'aliyun':
          config = this.aliyunConfig;
          cloudName = '阿里云OSS';
          break;
        case 'qiniu':
          config = this.qiniuConfig;
          cloudName = '七牛云';
          break;
        case 'tencent':
          config = this.tencentConfig;
          cloudName = '腾讯云COS';
          break;
      }

      // 简单验证配置是否填写完整
      const isComplete = Object.values(config).every(value => value !== '');
      if (!isComplete) {
        this.$message.warning('请先填写完整的配置信息');
        return;
      }

      try {
        this.$message.loading('正在测试连接，请稍候...', 0);
        const result = await testStorageConnection(type, config);

        if (result.success) {
          this.$message.success(`${cloudName}连接测试成功`);
        } else {
          this.$message.error(`${cloudName}连接测试失败: ${result.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('测试连接失败:', error);
        this.$message.error(`${cloudName}连接测试失败，请检查配置信息`);
      }
    }
  }
};
</script>

<style scoped>
.tabs-demo-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.demo-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.demo-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.card-header i {
  margin-right: 8px;
  color: #1890ff;
}

.storage-tabs {
  margin-top: 10px;
}

.tab-content {
  padding: 25px;
  background-color: #fff;
  border-radius: 4px;
}

.config-form {
  max-width: 800px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  transition: border-color 0.2s ease-in-out;
}

.form-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.el-button--primary {
  padding: 8px 20px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.4);
}

::v-deep .el-tabs__item {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}

::v-deep .el-tabs__item.is-active {
  color: #1890ff;
  font-weight: 500;
}

::v-deep .el-tabs__active-bar {
  background-color: #1890ff;
  height: 2px;
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

::v-deep .el-input__inner {
  border-radius: 4px;
  height: 38px;
  line-height: 38px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* 让标题和选择区左右分布 */
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding: 15px 20px;
  /* 增加头部内边距 */
}

/* 新增：默认存储选择区样式 */
.default-storage-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  /* 选择器和问号图标之间的间距 */
}

.default-storage-selector .el-select {
  width: 180px;
  /* 固定选择器宽度 */
}

.default-storage-selector .el-icon-question-circle {
  color: #1890ff;
  cursor: help;
  font-size: 16px;
}
</style>